import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { MulterOptionsFactory } from '@nestjs/platform-express';
import { MulterOptions } from '@nestjs/platform-express/multer/interfaces/multer-options.interface';
import * as multer from 'multer';
import * as path from 'path';
// https://blog.csdn.net/w84647517/article/details/135866668

// console.log('-------multer: ', multer);
// console.log('-------path: ', path);

// console.log('----rootDir: ', path.resolve(__dirname, '../../..'));

@Injectable()
export class MulterConfigService implements MulterOptionsFactory {
  constructor(private readonly configServise: ConfigService) {}

  createMulterOptions(): MulterOptions | Promise<MulterOptions> {
    const projectRootDir = path.resolve(__dirname, '../../..');
    console.log('--------projectRootDir: ', projectRootDir);

    const destDir = this.configServise.get('UPLOAD.DEST');

    const UPLOAD_DIR = path.join(projectRootDir, destDir);

    // console.log('----------UPLOAD_DIR: ', UPLOAD_DIR);

    return {
      storage: multer.diskStorage({
        destination: function (req, file, cb) {
          cb(null, UPLOAD_DIR);
        },
        filename: function (req, file, cb) {
          // console.log('-----createMulterOptions------file: ', file);
          const extName = path.extname(file.originalname);
          // console.log('------ext: ', extName);

          const uniqueSuffix =
            Date.now() + '-' + Math.round(Math.random() * 1e9);
          cb(null, file.fieldname + '-' + uniqueSuffix + extName);
        },
      }),
    };
  }
}
